package com.library.common.util;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

/**
 * IPage<T> 转IPage<V>封装工具类
 *
 * @author: xyh
 * @create: 2023-09-02
 **/
public class PageCovertUtil {

    /**
     * 将PageInfo对象泛型中的Po对象转化为Vo对象
     *
     * @param pageInfo PageInfo<Po>对象</>
     * @param <V>      V类型
     * @return
     */
    public static <P, V> IPage<V> pageVoCovert(IPage<P> pageInfo, Class<V> v) {
        try {
            if (pageInfo != null) {
                IPage<V> page = new Page<>(pageInfo.getCurrent(), pageInfo.getSize());
                page.setTotal(pageInfo.getTotal());
                List<P> records = pageInfo.getRecords();
                List<V> list = new ArrayList<>();
                for (P record : records) {
                    if (record != null) {
                        V newV = v.newInstance();
                        BeanUtil.copyProperties(record, newV);
                        list.add(newV);
                    }
                }
                page.setRecords(list);
                page.setTotal(pageInfo.getTotal());
                return page;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
